var JSObject = {
    calendar:null,
    cal_obj_event:{},
    open_popovers:{},
    curr_event_obj:null,

    init:function () {
        var self = this;

        self.calendar = $('#schedule_appointments').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            buttonText: {
                prev: '&laquo;',
                next: '&raquo;',
                prevYear: '&nbsp;&lt;&lt;&nbsp;',
                nextYear: '&nbsp;&gt;&gt;&nbsp;',
                today: 'today',
                month: 'month',
                week: 'week',
                day: 'day'
            },
            weekends:false,
            disableResizing:true,
            selectable: true,
            selectHelper: true,
            dayRender:function( date, cell ) {
                var date = new Date(date);
                var month_day = date.format("mm-dd");
               // $(cell).addClass('holiday-color');
                //console.log(month_day)
            },
            select: function(start, end, allDay) {
                self.resetAppForm();
                $(".hide-me").show();
                var cur_date = new Date();
                var cur_date_str = cur_date.format("yyyy-mm-dd");
                var date = new Date(start);
                var date_str = date.format("yyyy-mm-dd");
                var next_service_date = date_str;
                var $cl = '#333';//default
                var editable = true;
                if(date_str > cur_date_str){//future
                    $cl = '#0866c6';//blue
                }
                else if(date_str === cur_date_str){//present
                    $cl = '#fcb904';//yellow
                    editable = false;
                }
                else{ // past
                    $cl = '#dd0000';//red
                    editable = false;
                }
                var rtrn = true;
                //validate if date is in the past
                if(date_str < cur_date_str){//past
                    jQuery.alerts.dialogClass = 'alert-warning';
                    jConfirm('Are you sure you want to create an appointment in the past, '+date_str+' ?', 'Confirm', function(confirmation) {
                        if(confirmation){
                            $('#appointment_modal #id').val(0);
                            $('#appointment_modal #next_service_date').val(next_service_date);

                            self.cal_obj_event =  {
                                start: start,
                                end: end,
                                allDay: allDay,
                                color:$cl,
                                editable:editable
                            }
                            $('#appointment_modal').modal({
                                backdrop: 'static',
                                show: true,
                                keyboard: true
                            });
                        }
                        jQuery.alerts.dialogClass = null; // reset to default
                    });
                }
                else{
                    $('#appointment_modal #id').val(0);
                    $('#appointment_modal #next_service_date').val(next_service_date);

                    self.cal_obj_event =  {
                        start: start,
                        end: end,
                        allDay: allDay,
                        color:$cl,
                        editable:editable
                    }
                    $('#appointment_modal').modal({
                        backdrop: 'static',
                        show: true,
                        keyboard: true
                    });
                }
            },
            editable: true,
            eventRender: function (event, element) {
                element.find('.fc-event-title').html(event.title);//To Allow html tags
                var btns = event.btns
                if(!event.editable){
                    btns = event.btns2
                }
                element.popover({
                    title: event.title,
                    placement:event.start.getHours()>12?'top':'bottom',
                    container:'body',
                    trigger:'manual',
                    html:true,
                    content: event.format_content+btns
                });
            },
            eventClick: function(calEvent, jsEvent, view) {
                self.curr_event_obj = calEvent;
                self.manageClickPopovers(calEvent,$(this),'toggle','toggle');
            },
            eventDragStart: function( calEvent, jsEvent, ui, view ) {
                //self.curr_event_obj = calEvent;
                //self.manageClickPopovers(calEvent,$(this),'hide','hide');
            },
            eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
                //self.manageClickPopovers(event,$(this),'hide','hide');
                self.dropAppointment(event,revertFunc);
            },
            events:{
                url:  $("#get_appointment_url").val(),
                type: 'GET',
                error: function() {
                    var txt = 'There was an error while fetching appointments!'
                    jLib.serverError(txt);
                }
            }
        });

        //appointment_btn
        $("#appointment_modal #form-appointment").submit(function(e) {
            e.preventDefault();
            self.saveAppointment();
        });

        $(".edit_app_btn").live('click',function(){
            var id_from_btn = $(this).attr('data-id');

            var id = self.curr_event_obj.id;
            var dt = new Date(self.curr_event_obj.start);
            var next_service_date = dt.format("yyyy-mm-dd");
            /*var enddt = self.curr_event_obj.end_date;
            var end_date = '';
            if(enddt.length > 0){
                var end_dt = new Date(enddt);
                var end_date = end_dt.format("yyyy-mm-dd");
            }*/
            var reminder_time = self.curr_event_obj.reminder_time;
            var customer_id =  self.curr_event_obj.customer_id;
            var vehicle_number = self.curr_event_obj.vehicle_number;
            var vehicle_type = self.curr_event_obj.vehicle_type;
            var parent_id = self.curr_event_obj.parent_id;
            var repeat = self.curr_event_obj.repeat;
            var repeat_freq = self.curr_event_obj.repeat_freq;

            $('#appointment_modal #id').val(id);
            $('#appointment_modal #parent_id').val(parent_id);
            $('#appointment_modal #repeat').val(repeat);
            $('#appointment_modal #repeat_freq').val(repeat_freq);
            $('#appointment_modal #customer_id').val(customer_id);
            $('#appointment_modal #vehicle_number').val(vehicle_number);
            $('#appointment_modal #vehicle_type').val(vehicle_type);
            $('#appointment_modal #next_service_date').val(next_service_date);
            //$('#appointment_modal #end_date').val(end_date);
            $('#appointment_modal #reminder_time').val(reminder_time);

            console.log(self.curr_event_obj);

            $(".hide-me").hide();
            $('#appointment_modal').modal({
                backdrop: 'static',
                show: true,
                keyboard: true
            });
            $(self.open_popovers[id]).popover('hide');
            delete self.open_popovers[id];
        });

        $(".close_app_btn").live('click',function(){
            var id = $(this).attr('data-id');
            $(self.open_popovers[id]).popover('hide');
            delete self.open_popovers[id];
        });
        $(".delete_app_btn").live('click',function(){
            var id = $(this).attr('data-id');
            $(self.open_popovers[id]).popover('hide');
            delete self.open_popovers[id];
            self.deleteAppointment(id);
        });

        $(".turned-up-btn").live('click',function(){
            var id = $(this).attr('data-id');
            self.turnedUpAppointment(id,$(this));
        });
    },

    resetAppForm: function(){
        document.getElementById('form-appointment').reset();
        $('#appointment_modal #id').val('0');
        $('#appointment_modal #parent_id').val('0');
        $('#appointment_modal #repeat').val('No');
        $('#appointment_modal #repeat_freq').val('');
        $('#appointment_modal #customer_id').val('');
        $('#appointment_modal #vehicle_number').val('');
        $('#appointment_modal #vehicle_type').val('');
        $('#appointment_modal #next_service_date').val('');
        //$('#appointment_modal #end_date').val(end_date);
        $('#appointment_modal #reminder_time').val('');
    },

    manageClickPopovers: function(eventObj,cur_obj,first_status,status){
        var self  = this;
        var id = eventObj.id
        if(self.open_popovers[id] == undefined){//New
            for(var x in self.open_popovers){
                $(self.open_popovers[x]).popover('hide');
                delete self.open_popovers[x];
            }
            $(cur_obj).popover(first_status);
            self.open_popovers[id] = cur_obj;
        }
        else{//if exist
            $(cur_obj).popover(status);
        }
    },

    saveAppointment: function() {
        var self = this;
        var query = $("#appointment_modal #form-appointment").serialize();
        var url = $("#appointment_modal #appointment_btn").attr("href");
        var $lbl = ' Service Appointment';
        $.ajax({
            type: 'post',
            url: url,
            data: query,
            dataType: 'json',
            success: function(response) {
                var txt = '';
                if (typeof response.msg == 'object') {
                    for (var megTxt in response.msg) {
                        txt += response.msg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.msg
                }
                if(response.code == 0){
                   /* var id = $('#appointment_modal #id').val();
                    var sid = response.id;
                    var customer_id = $("#appointment_modal #customer_id").val();
                    var vehicle_number = $("#appointment_modal #vehicle_number").val();
                    var vehicle_type = $("#appointment_modal #vehicle_type").val();
                    var next_service_date = $("#appointment_modal #next_service_date").val();
                    var dt = new Date(next_service_date);
                    var reminder_time = $("#appointment_modal #reminder_time").val();
                    var reminder_time_name = $("#appointment_modal #reminder_time option:selected").text();
                    var render_obj = self.cal_obj_event;
                    var title = '<b>'+$("#appointment_modal #customer_id option:selected").text()+'</b>:'+$lbl;*/
                   /* var end_date = $("#appointment_modal #end_date").val();
                    var end_date = end_date.trim();
                    var end_dt_ui = '';
                    if(end_date.length > 0){
                        var end_dt = new Date(end_date);
                        end_dt_ui = end_dt.format("mmmm dd, yyyy");
                    }*/

                    /*var btns = "<hr style='margin: 8px 0px;' />";
                    btns += "<button class='btn btn-small edit_app_btn' data-id='"+sid+"'> Edit </button>";
                    btns += "<button class='btn btn-small delete_app_btn' data-id='"+sid+"'> Delete </button>";
                    btns += "<button class='btn btn-small close_app_btn' data-id='"+sid+"'> Close </button>";

                    var btns2 = "<hr style='margin: 8px 0px;' />";
                    btns2 += "<button class='btn btn-small delete_app_btn' data-id='"+sid+"'> Delete </button>";
                    btns2 += "<button class='btn btn-small close_app_btn' data-id='"+sid+"'> Close </button>";

                    var format_content = "<b>When</b>: "+dt.format('mmmm dd, yyyy')+"<br /> ";
                    *//*format_content   += "<b>End</b>: "+end_dt_ui+"<br /> ";*//*
                    format_content   += "<b>Remind Me in</b>: "+reminder_time_name+"<br /> ";
                    format_content   +="<b>Vehicle Number</b>: "+vehicle_number+"<br /> ";
                    format_content   +="<b>Vehicle Type</b>: "+vehicle_type;*/

                    if(id == 0){//New appointment
                        /*render_obj['title'] = title;
                        render_obj['btns'] = btns;
                        render_obj['id'] = sid;*/
                        /*if(end_date.length > 0){
                            render_obj['end_date'] = end_date;
                        }
                        else{
                            render_obj['end_date'] = '';
                        }*/
                        /*render_obj['customer_id'] = customer_id;
                        render_obj['reminder_time'] = reminder_time;
                        render_obj['vehicle_number'] = vehicle_number;
                        render_obj['vehicle_type'] = vehicle_type;
                        render_obj['format_content'] = format_content;*/
                        /*self.calendar.fullCalendar('renderEvent',
                            render_obj,
                            true // make the event "stick"
                        )*/
                        /*self.calendar.fullCalendar('unselect');*/
                        $("#appointment_modal").modal("hide");
                    }
                    else{//Editing Existing
                        /*var cur_date = new Date();
                        var cur_date_str = cur_date.format("yyyy-mm-dd");
                        var date = new Date(next_service_date);
                        var date_str = date.format("yyyy-mm-dd");

                        var $cl = '#333';//default
                        var editable = true;
                        if(date_str > cur_date_str){//future
                            $cl = '#0866c6';//blue
                        }
                        else if(date_str === cur_date_str){//present
                            $cl = '#fcb904';//yellow
                            editable = false;
                        }
                        else{ // past
                            $cl = '#dd0000';//red
                            editable = false;
                        }

                        self.curr_event_obj.start = dt;*/
                        /*if(end_date.length > 0){
                            self.curr_event_obj.end_date = end_date;
                        }
                        else{
                            self.curr_event_obj.end_date = '';
                        }*/
                        /*self.curr_event_obj.color = $cl;
                        self.curr_event_obj.title = title;
                        self.curr_event_obj.btns = btns;
                        self.curr_event_obj.id = id;
                        self.curr_event_obj.editable = editable;
                        self.curr_event_obj.customer_id = customer_id;
                        self.curr_event_obj.reminder_time = reminder_time;
                        self.curr_event_obj.vehicle_number = vehicle_number;
                        self.curr_event_obj.vehicle_type = vehicle_type;
                        self.curr_event_obj.format_content = format_content;*/

                        //self.calendar.fullCalendar('updateEvent', self.curr_event_obj);

                        $("#appointment_modal").modal("hide");
                    }

                    self.calendar.fullCalendar( 'refetchEvents' );
                    jLib.serverSuccess(txt);
                }
                else{
                    jLib.serverError(txt);
                }
            },
            error: function() {
                jLib.serverError();
            }
        });
    },

    deleteAppointment:function(id){
        var self = this;

        jQuery.alerts.dialogClass = 'alert-warning';
        jConfirm('Are you sure you want to delete this appointment ?', 'Confirm', function(confirmation) {
            if(confirmation){
                var query = "id="+id;
                var url = $("#delete_appointment_url").val();
                $.ajax({
                    type: 'post',
                    url: url,
                    data: query,
                    dataType: 'json',
                    success: function(response) {
                        var txt = '';
                        if (typeof response.msg == 'object') {
                            for (var megTxt in response.msg) {
                                txt += response.msg[megTxt] + '<br />';
                            }
                        }
                        else {
                            txt = response.msg
                        }
                        if(response.code == 0){
                            jLib.serverSuccess(txt);
                            self.calendar.fullCalendar( 'removeEvents',self.curr_event_obj.id );
                        }
                        else{
                            jLib.serverError(txt);
                        }
                    },
                    error: function() {
                        jLib.serverError();
                    }
                });
            }
            jQuery.alerts.dialogClass = null; // reset to default
        });
    },


    turnedUpAppointment:function(id,btn){
        var self = this;

        jQuery.alerts.dialogClass = 'alert-warning';
        jConfirm('Are you sure the customer has turned up ?', 'Confirm', function(confirmation) {
            if(confirmation){
                var query = "id="+id;
                var url = $("#turned_up_appointment_url").val();
                $.ajax({
                    type: 'post',
                    url: url,
                    data: query,
                    dataType: 'json',
                    success: function(response) {
                        var txt = '';
                        if (typeof response.msg == 'object') {
                            for (var megTxt in response.msg) {
                                txt += response.msg[megTxt] + '<br />';
                            }
                        }
                        else {
                            txt = response.msg
                        }
                        if(response.code == 0){
                            jLib.serverSuccess(txt);
                            btn.parent().addClass('turned-up');
                            btn.remove();
                        }
                        else{
                            jLib.serverError(txt);
                        }
                    },
                    error: function() {
                        jLib.serverError();
                    }
                });
            }
            jQuery.alerts.dialogClass = null; // reset to default
        });
    },

    dropAppointment:function(event,revertFunc){
        var self = this;

        var cur_date = new Date();
        var cur_date_str = cur_date.format("yyyy-mm-dd");
        var date = new Date(event.start);
        var date_str = date.format("yyyy-mm-dd");
        var ui_date = date.format("mmmm dd, yyyy");
        /*var end_dt_ui = '';
        if(event.end_date.length > 0){
            var end_dt = new Date(event.end_date);
            end_dt_ui = end_dt.format("mmmm dd, yyyy");
        }*/

        var query = "id="+event.id+"&next_service_date="+date_str+"&reminder_time="+event.reminder_time;
        var url = $("#update_appointment_url").val();
        $.ajax({
            type: 'post',
            url: url,
            data: query,
            dataType: 'json',
            success: function(response) {
                var txt = '';
                if (typeof response.msg == 'object') {
                    for (var megTxt in response.msg) {
                        txt += response.msg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.msg
                }
                if(response.code == 0){
                    jLib.serverSuccess(txt);
                    var $cl = '#333';//default
                    if(date_str > cur_date_str){//future
                        $cl = '#0866c6';//blue
                    }
                    else if(date_str === cur_date_str){//present
                        $cl = '#fcb904';//yellow
                    }
                    else{ // past
                        $cl = '#dd0000';//red
                    }

                    var format_content = "<b>When</b>: "+ui_date+"<br /> ";
                    /*format_content   += "<b>End</b>: "+end_dt_ui+"<br /> ";*/
                    format_content   += "<b>Remind Me in</b>: "+reminder_time_list[event.reminder_time]+"<br /> ";
                    format_content   +="<b>Vehicle Number</b>: "+event.vehicle_number+"<br /> ";
                    format_content   +="<b>Vehicle Type</b>: "+event.vehicle_type;
                    event.color = $cl;
                    event.format_content = format_content;
                    self.calendar.fullCalendar('updateEvent', event);
                }
                else{
                    jLib.serverError(txt);
                    revertFunc();
                }
            },
            error: function() {
                jLib.serverError();
            }
        });

        /*if(date_str < cur_date_str){//past
            jQuery.alerts.dialogClass = 'alert-warning';
            jConfirm('Are you sure you want to move this appointment to the past, '+date_str+' ?', 'Confirm', function(confirmation) {
                if(confirmation){


                }
                jQuery.alerts.dialogClass = null; // reset to default
            });
        }*/
    }



};

/* when the page is loaded */
$(document).ready(function () {
    JSObject.init();
});